#!/bin/bash

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/../common.sh"

function install_development() {
  sudo yum install -y wget tar environment-modules readline-devel libXt-devel \
    bzip2-devel xz-devel libcurl-devel glibc-headers gcc-c++ pcre* -y
  source /etc/profile
}

function download_R() {
  echo "# R正在下载"
  wget -t 0 -T 20 -c -P "$1" http://mirror.bjtu.edu.cn/cran/src/base/R-4/R-4.2.0.tar.gz
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# R已经下载成功\033[0m"
  else
    echo -e "\033[31m# R下载失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

function install_R() {
  echo "# R 正在安装"
  tar -xzf "$1"/R-4.2.0.tar.gz -C "$1" && rm -rf "$1"/R-4.2.0.tar.gz
  cd "$1"/R-4.2.0
  FC=flang CC=clang CXX=clang++ ./configure --enable-R-shlib=yes --with-tcltk --prefix="$2"/R-4.2.0
  make -j"$(nproc)" && make install
  echo -e "\033[1;32;1m# R 已经安装完毕\033[0m"
}

function write_R_module() {
  cat >"$1/R-4.2.0/R-4.2.0_modulefiles" <<EOF
#%Module1.0
conflict R
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
  variable modfile
  set modfile_path [file dirname \$modfile]
  return \$modfile_path
}
set pwd [getModulefileDir]
set R \$pwd
setenv R \$R
prepend-path PATH \$R/bin
prepend-path LIBRARY_PATH \$R/lib
prepend-path LD_LIBRARY_PATH \$R/lib
EOF
}

function main() {
  set -e
  is_check_build_install_directory "$1" "$2" "R-4.2.0.sh"
  is_check_build_equal "$1" "$2"
  install_development
  download_R "$1"
  install_R "$1" "$2"
  write_R_module "$2"
  rm -rf "$1"/R-4.2.0
}

main "$@"
